package com.qianfeng.plateform2203.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.plateform2203.common.constants.RedisConstants;
import com.qianfeng.plateform2203.zuul.feign.CacheService;
import com.qianfeng.plateform2203.zuul.utils.ZuulUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

@Component
public class SystemParamsFilter extends ZuulFilter {

    @Autowired
    CacheService cacheService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 9;
    }

    @Override
    public boolean shouldFilter() {
        final RequestContext currentContext = RequestContext.getCurrentContext();
        return currentContext.sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {

        // 请求参数是否完备
        final RequestContext currentContext = RequestContext.getCurrentContext();
        final HttpServletRequest request = currentContext.getRequest();

        // 获取必传参数的集合
        String key = RedisConstants.API_PARAM_PRE;
        Set<Object> systemParamSet = null;
        try {
            systemParamSet = cacheService.sMembers(key);

            // 获取本次请求对象中所有参数的集合
            final Set<String> requestParamSet = request.getParameterMap().keySet();

            // 集合的减法
            systemParamSet.removeAll(requestParamSet);

            // 判断是否还有剩余元素
            if (systemParamSet.size()==0){
                return null; // 必传参数都传了
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        // 请求有问题，不允许请求继续发给后面的微服务了
        ZuulUtils.sentErrorRespons(currentContext,"必传参数不完整，请检查参数个数"+systemParamSet);


        return null;
    }
}
